<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card>
      <!-- 添加按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addcate">
            添加数据
          </el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <tree-table
        :data="list"
        :columns="columns"
        index-text=""
        show-index
        border
        stripe
        :expand-type="false"
        :selection-type="false"
        :show-row-hover="false"
        class="bt"
      >
        <!-- 自定义排序列 -->
        <template slot="cat_level" scope="{row}">
          <el-tag v-if="row.cat_level == 0">一级</el-tag>
          <el-tag type="warning" v-else-if="row.cat_level == 1">二级</el-tag>
          <el-tag type="danger" v-else>三级</el-tag>
        </template>
        <!-- 自定义是否有效列 -->
        <template slot="cat_deleted" scope="{row}">
          <span
            class="el-icon-error errorstyle"
            v-if="row.cat_deleted == 'false'"
            >无效</span
          >
          <i class="el-icon-success" style="color:lightgreen" v-else></i>
        </template>
        <!-- 操作slot为下面定义的插槽名 -->
        <template slot="set" scope="{row}">
          <!-- {{ row.cat_id }} -->
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="setcat(row.cat_id)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="delbtn(row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInof.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInof.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 添加对话框 -->
      <el-dialog
        title="添加分类"
        :visible.sync="addcatedialogVisible"
        width="50%"
        @close="addclose"
      >
        <span>
          <el-form
            :model="addform"
            :rules="addcaterules"
            ref="addcateref"
            label-width="100px"
          >
            <!-- 分类名称输入框 -->
            <el-form-item label="分类名称" prop="catenamer">
              <el-input v-model="addform.cateName"></el-input>
            </el-form-item>

            <!-- 级联选中框 -->
            <el-form-item>
              <el-cascader
                v-model="selectvalue"
                :options="editForm"
                :props="addcateprops"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addcatedialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addyes">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 删除商品对话框 -->
      <el-dialog title="删除商品" :visible.sync="setbtn" width="50%">
        <span>
          <el-form
            :model="setvalue"
            :rules="addcaterules"
            ref="setruleForm"
            label-width="100px"
          >
            <el-form-item label="活动名称" prop="catenamer">
              <el-input v-model="setvalue.cat_name"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setbtn = false">取 消</el-button>
          <el-button type="primary" @click="setyes">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: '',
  data() {
    return {
      queryInof: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      //数据列表数组
      list: [],
      // 总条数
      total: 0,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          type: 'template',
          template: 'cat_deleted'
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'cat_level'
        },
        {
          label: '操作',

          type: 'template',
          template: 'set'
        }
      ],
      // 修改弹出框默认值
      addcatedialogVisible: false,
      //验证规则
      addcaterules: {
        catenamer: [
          { required: false, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      // 双向绑定输入框
      addform: {
        cateName: ''
      },
      //后台2级目录的数据
      editForm: [],
      // 被级联选择框选中的id所组成的数组
      selectvalue: [],
      // 级联选中框的配置对象
      addcateprops: {
        expandTrigger: 'hover',
        checkStrictly: true,
        value: 'cat_id',
        label: 'cat_name'
      },
      // 默认删除对话框为关闭
      setbtn: false,
      // 要设置的id值
      setid: null,
      setvalue: {
        // setname: ""
      }
    }
  },
  created() {
    this.getGoodsCate()
  },
  // mounted () {},
  computed: {},
  watch: {},
  methods: {
    //封装获取数据刷新视图
    async getGoodsCate() {
      const { data: res } = await this.$http.get(`categories`, {
        params: this.queryInof
      })
      if (res.meta.status !== 200) {
        return this.$message.error('失败')
      }
      //总条数
      this.total = res.data.total
      // 数据列表数组
      this.list = res.data.result
    },
    //渲染页码
    handleSizeChange(val) {
      this.queryInof.pagesize = val
      this.getGoodsCate()
    },
    handleCurrentChange(val) {
      this.queryInof.pagenum = val
      this.getGoodsCate()
    },
    //弹出添加对话框
    async addcate() {
      const { data: res } = await this.$http.get('categories/', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败！')
      } // 注意editForm是data中定义的其值和表单双向绑定的对象
      this.editForm = res.data
      this.addcatedialogVisible = true
    },
    // 级联数据变化触发方法
    handleChange() {},
    //关闭对话框重置表达验证
    addclose() {
      this.$refs.addcateref.resetFields()
      this.addform = {}
      this.selectvalue = []
    },
    //添加分类
    async addyes() {
      if (!this.addform.cateName) {
        return this.$message.error('请填写分类名称')
      }
      const cat_pidId = this.selectvalue[this.selectvalue.length - 1]
        ? this.selectvalue[this.selectvalue.length - 1]
        : 0
      const cat_levelId = this.selectvalue.length
      console.log(cat_levelId)
      const { data: res } = await this.$http.post(`categories`, {
        cat_pid: cat_pidId,
        cat_level: cat_levelId,
        cat_name: this.addform.cateName
      })
      if (res.meta.status !== 201) {
        return this.$message.error('添加信息失败！')
      }
      this.$message.success('添加信息成功')
      this.getGoodsCate()
      this.addcatedialogVisible = false
    },
    // 点击设置按钮
    async setcat(id) {
      this.setid = id
      const { data: res } = await this.$http.get(`categories/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败！')
      }
      //给对象!!!!
      this.setvalue = res.data
      // console.log(res.data);
      this.setbtn = true
    },
    // 点击确定按钮修改
    setyes() {
      this.$refs.setruleForm.validate(async valid => {
        if (!valid) return // 可以发起添加用户的网络请求 注意addForm是data中定义的其值和表单双向绑定的对象
        const { data: res } = await this.$http.put(`categories/${this.setid}`, {
          cat_name: this.setvalue.cat_name
        })
        // console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error('更改用户失败！')
        }
        this.$message.success('更改用户成功！') // 隐藏添加用户的对话框???
        this.setbtn = false // 重新获取用户列表数据
        this.getGoodsCate()
      })
    },
    // 点击删除按钮
    async delbtn(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err) // 如果用户确认删除，则返回值为字符串 confirm // 如果用户取消了删除，则返回值为字符串 cancel // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`categories/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      this.getGoodsCate()
    }
  }
}
</script>

<style lang="less" scoped>
.successstyle {
  background-color: rgb(188, 241, 188);
}
.errorstyle {
  background-color: rgb(248, 188, 188);
}
.el-cascader {
  width: 100%;
}
.bt {
  margin-top: 20px;
}
</style>
